/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package cart.hibernate.genre;

/**
 *
 * @author BibooChung
 */
import cart.hibernate.HibernateUtil;
import java.util.List; 
import java.util.Iterator; 
 
import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class ManageGenre {
  
    public List getAllGenre() {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = null;
        List allGenre = null;
        try{
           tx = session.beginTransaction();
           allGenre = session.createQuery("FROM Genre").list(); 
           tx.commit();
        }catch (HibernateException e) {
           if (tx!=null) tx.rollback();
           e.printStackTrace(); 
        }finally {
           session.close(); 
        }
        return allGenre;
    }
    
    public int addGenre(String genreName) { 
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = null;
        int genreId = -1;

        try {
            tx = session.beginTransaction();
            Genre genre = new Genre(genreName);
            genreId = (Integer) session.save(genre);
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
        return genreId;
    }
    
    public void updateGenre(int genreId, String newGenre) {
        Session session = HibernateUtil.getSessionFactory().openSession();
    	Transaction tx = null;
    	try{
    	   tx = session.beginTransaction();
    	   Genre genre = (Genre)session.get(Genre.class, genreId); 
    	   genre.setGenreName(newGenre);
           session.update(genre);
    	   tx.commit();
    	}catch (HibernateException e) {
    	   if (tx!=null) tx.rollback();
    	   e.printStackTrace(); 
    	}finally {
    	   session.close(); 
    	}
    }

    public void deleteGenre(int genreId) {
    	Session session = HibernateUtil.getSessionFactory().openSession();
    	Transaction tx = null;
    	try{
    	   tx = session.beginTransaction();
    	   Genre genre = (Genre)session.get(Genre.class, genreId); 
    	   session.delete(genre); 
    	   tx.commit();
    	}catch (HibernateException e) {
    	   if (tx!=null) tx.rollback();
    	   e.printStackTrace(); 
    	}finally {
    	   session.close(); 
    	}
    }
}